# -*- coding: utf-8 -*- # 
import wx.lib.mixins.listctrl as listmix
import appimage as images
import wx
import sys

class SortedList(listmix.ColumnSorterMixin):
    def __init__(self, parent, id=-1):
        #self.il = wx.ImageList(16, 16)
        self.il = wx.ImageList(7, 6)

        self.sm_up = self.il.Add(images.getUpBitmap())
        self.sm_dn = self.il.Add(images.getDownBitmap())
    
        #完成组件的初始化
        self.init()
    
        self.list.SetImageList(self.il, wx.IMAGE_LIST_SMALL)

        listmix.ColumnSorterMixin.__init__(self, self.columns_num)
    
    def init(self):
        """组件初始化，其中生成ListCtrl时需要调用createlist方法用户需要覆盖此方法"""
        pass

    def initdata(self):
        """生成一个数据字典，值为每行记录的所有列的tuple，生成后需要返回用户需要覆盖此方法"""
        datamap = {}

    def createlist(self, columns):
        self.columns_num = len(columns)
        self.list = wx.ListCtrl(self, -1,
                                 style=wx.LC_REPORT
                                 | wx.LC_SINGLE_SEL
                                 )

        info = wx.ListItem()
        info.m_mask = wx.LIST_MASK_TEXT | wx.LIST_MASK_FORMAT

        for i, v in enumerate(columns):
            name, length, align = v
        
            if align == 'left':
                info.m_format = wx.LIST_FORMAT_LEFT
            elif align == 'center':
                info.m_format = wx.LIST_FORMAT_CENTER
            elif align == 'right':
                info.m_format = wx.LIST_FORMAT_RIGHT
            else:
                """Default = Left """
                info.m_format = wx.LIST_FORMAT_LEFT
            info.m_text = name
            self.list.InsertColumnInfo(i, info)
            self.list.SetColumnWidth(i, length)

        return self.list

    def loaddata(self):
        self.itemDataMap = self.initdata()
        items = self.itemDataMap.items()
        for key, data in items:
            data = map(self.str, data)
            index = self.list.InsertStringItem(sys.maxint, data[0])
            for i, t in enumerate(data[1:]):
                self.list.SetStringItem(index, i+1, t)
            self.list.SetItemData(index, key)
        return len(self.itemDataMap)

    def str(self, s):
        if isinstance(s, (int, float, long)) :
            return "%s" % str(s)
        else:
            return s

    def GetListCtrl(self):
        return self.list

    def GetSortImages(self):
        return (self.sm_dn, self.sm_up)